#include <unistd.h>
#include <stdio.h>
#include <math.h>
#include <iostream>
#include <string>
#include <list>
#include <fstream>
#include<iostream>

#include <iostream>
#include <fstream>

#include <string>

#include "time.h"

#include "opencv2/opencv.hpp"
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"

using namespace cv;

typedef unsigned char U_CHAR;

using namespace std;

typedef struct  locs  {
    int x;
    int y;
    int w;
    int h;
    int score;
    int classID;
}locs;

void split(const string& s,vector<int>& sv,const char flag = ' ') {
    sv.clear();
    istringstream iss(s);
    string temp;

    while (getline(iss, temp, flag)) {
        sv.push_back(stoi(temp));
    }
    return;
}

int timecount(){


    time_t start,end;
    start = time(NULL);
    system("python3 /mnt/data/3519/caffeCvtTools/nnie_bgr/nnie2bgr.py");
    end = time(NULL);
    printf("The pause used %f seconds",difftime(end,start));

    return 0;

}

int main()
{
    std::string  filename = "/mnt/data/3519/caffeCvtTools/nnie_bgr/222.png";
    std::string name = "222";
    std::string outname = "/mnt/data/3519/caffeCvtTools/nnie_bgr/data/"+name+"416.bgr";

    cv::Mat img = cv::imread(filename);
    cv::Mat origion = img.clone();
    cv::imwrite("/mnt/data/3519/caffeCvtTools/nnie_bgr/data/"+name+".jpg",origion);


    if (img.empty())
    {

        printf("reading image file fails \n");
        return 1;
    }
    int net_w, net_h;
    net_w = 416;
    net_h = 416;

    int new_w, new_h;
    if (((float)net_w / img.cols) < ((float)net_h / img.rows)) {
        new_w = net_w;
        new_h = (img.rows * new_w) / img.cols;
    }
    else {
        new_h = net_h;
        new_w = (img.cols * net_h) / img.rows;
    }
    Mat resized;
    cv::resize(img, resized, Size(new_w, new_h));

    Mat box = Mat(Size(net_w, net_h), CV_MAKETYPE(CV_8U, img.channels()), Scalar::all(127));
    Mat roi(box, Rect((net_w - new_w) >> 1, (net_h - new_h) >> 1, new_w, new_h));
    resized.copyTo(roi);

    int w=roi.cols;
    int h = roi.rows;
    cv::Mat back = cv::Mat::zeros(416, 416, CV_8UC3);
    roi.copyTo(back(cv::Rect(0,0,w,h)));
    cv::imwrite("/mnt/data/3519/caffeCvtTools/nnie_bgr/data/roi.jpg",back);


    cv::Mat imgResize = back;
    if (!img.data)
    {
        printf("read image error\n");
        return -1;
    }

    cv::imwrite("/mnt/data/3519/caffeCvtTools/nnie_bgr/data/"+name+"416.jpg",imgResize);


    U_CHAR *data = (U_CHAR*)imgResize.data;
    int step = imgResize.step;
    printf("Step: %d, height: %d, width: %d\n",
           step, img.rows, img.cols);

    FILE *fp = fopen(outname.c_str(), "wb");
    int hh = imgResize.rows;
    int ww = imgResize.cols;
    int c = imgResize.channels();

    for (int k = 0; k<c; k++) {
        for (int i = 0; i<hh; i++) {
            for (int j = 0; j<ww; j++) {
                fwrite(&data[i*step + j*c + k], sizeof(U_CHAR), 1, fp);
            }
        }
    }
    fclose(fp);

    return 0;


}
